package info.ask4research.web;

import info.ask4research.model.UnitOfLearning;
import info.ask4research.model.activities.Activity;
import info.ask4research.model.addons.Addon;
import info.ask4research.model.addons.Answer;
import info.ask4research.model.addons.MultipleChoice;
import info.ask4research.model.addons.Question;
import info.ask4research.model.addons.QuestionsAndAnswers;
import info.ask4research.model.addons.TextWork;
import info.ask4research.model.addons.UploadingFiles;
import info.ask4research.model.enums.Effort;
import info.ask4research.model.roles.Role;
import info.ask4research.model.toolsAndMaterials.ForumService;
import info.ask4research.service.IActivityService;
import info.ask4research.service.IAddonService;
import info.ask4research.service.IAnswerService;
import info.ask4research.service.IMultipleChoiceService;
import info.ask4research.service.IQuestionService;
import info.ask4research.service.IUnitOfLearningService;
import info.ask4research.web.dto.AddonDTO;
import info.ask4research.web.dto.EditAddonDTO;
import info.ask4research.web.dto.ToolsAndMaterialsRolesDTO;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class AddonController {

	private IUnitOfLearningService unitOfLearningService;
	private IAddonService addonService;
	private IQuestionService questionService;
	private IActivityService activityService;
	private IAnswerService answerService;
	private IMultipleChoiceService multipleChoiceService;


	@RequestMapping(value="jsp/addons/saveAddonUploadingFilesAttributes.action")
	public @ResponseBody Map saveAddonUploadingFilesAttributes(
			@RequestParam(value="effort") Integer effort,
			@RequestParam(value="maxPersons") Integer maxPersons,
			@RequestParam(value="minPersons") Integer minPersons,
			@RequestParam(value="text") String text,
			HttpSession session) throws Exception {

		UnitOfLearning unitOfLearning = unitOfLearningService.get((Integer)session.getAttribute("unitOfLearningId"));
		boolean uploadingFilesExist = addonService.uploadingFilesExists(text,(Integer)session.getAttribute("unitOfLearningId"));
		Map<String,Object> modelMap = new HashMap<String,Object>(3);
		UploadingFiles uploadingFiles = new UploadingFiles();
		if(uploadingFilesExist){
			uploadingFiles = (UploadingFiles) addonService.getAddonByUoFandRoleName(text,(Integer)session.getAttribute("unitOfLearningId"));
		}
		if(unitOfLearning != null ){

			uploadingFiles.setTitle(text);
			uploadingFiles.setEffort(Effort.valueOf(effort));
			uploadingFiles.setMaximum(maxPersons);
			uploadingFiles.setMinimum(minPersons);
			uploadingFiles.setUnitOfLearning(unitOfLearning);
			addonService.save(uploadingFiles);

			modelMap.put("total", 1);
			modelMap.put("uploadingFiles", uploadingFiles);
			modelMap.put("success", true);
		} else {
			modelMap.put("total", 0);
			modelMap.put("data", null);
			modelMap.put("failure", false);
		}

		return modelMap;
	}


	@RequestMapping(value="jsp/addons/saveAddonQuestionsAttributes.action")
	public @ResponseBody Map saveAddonQuestionsAttributes(
			//			@RequestParam(value="effort") Integer effort,
			//			@RequestParam(value="maxPersons") Integer maxPersons,
			@RequestParam(value="node") String node,
			@RequestParam(value="text") List<String> text,
			HttpSession session) throws Exception {

		int unitOfLearningId = (Integer)session.getAttribute("unitOfLearningId");
		//		boolean uploadingFilesExist = addonService.uploadingFilesExists(text,(Integer)session.getAttribute("unitOfLearningId"));
		QuestionsAndAnswers questionsAndAnswers = (QuestionsAndAnswers) addonService.getAddonByUoFandRoleName(node, unitOfLearningId);
		Map<String,Object> modelMap = new HashMap<String,Object>(3);
		List<Question> questions = new ArrayList<Question>();	
		if(String.valueOf(unitOfLearningId) != null ){
			for(String questionTitle : text){
				Question question = new Question();
				question.setQuestion(questionTitle);

				question = questionService.save(question);
				questions.add(question);
			}
			questionsAndAnswers.setQuestions(questions);

			addonService.save(questionsAndAnswers);

			modelMap.put("total", 1);
			//modelMap.put("uploadingFiles", uploadingFiles);
			modelMap.put("success", true);
		} else {
			modelMap.put("total", 0);
			modelMap.put("data", null);
			modelMap.put("failure", false);
		}

		return modelMap;
	}

	@RequestMapping(value="jsp/addons/saveAddonMcTQuestionsAttributes.action")
	public @ResponseBody Map saveAddonMcTQuestionsAttributes(
			@RequestParam(value="answer") List<String> answer,
			@RequestParam(value="node") String node,
			@RequestParam(value="question") List<String> questions,
			HttpSession session,HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		int unitOfLearningId = (Integer)session.getAttribute("unitOfLearningId");
		MultipleChoice multipleChoice = (MultipleChoice)addonService.getAddonByUoFandRoleName(node, unitOfLearningId);
		Map<String,Object> modelMap = new HashMap<String,Object>(3);
		List<Question> questionz = new ArrayList<Question>();	
		if(String.valueOf(unitOfLearningId) != null && multipleChoice!=null){
			for(int i=0; i<questions.size(); i++){
				Question question = new Question();
				question.setQuestion(questions.get(i));
				String answers = answer.get(i);
				if(StringUtils.isNotEmpty(answers)){
					List<Answer> savedAnswers = new ArrayList<Answer>();
					String[] ans = answers.split(",");
					for(int k =0; k<ans.length; k++){
						Answer answer2 = new Answer();
						answer2.setAnswer(ans[k]);
						answer2 = answerService.save(answer2);
						savedAnswers.add(answer2);
					}
					question.setAnswers(savedAnswers);
					question = questionService.save(question);
					questionz.add(question);
				}

				multipleChoice.setQuestions(questionz);
				multipleChoiceService.save(multipleChoice);
			}

			modelMap.put("total", 1);
			modelMap.put("success", true);
		} else {
			modelMap.put("total", 0);
			modelMap.put("data", null);
			modelMap.put("failure", false);
		}

		return modelMap;
	}


	@RequestMapping(value="jsp/addons/getMtcQuestionAttributes.action")
	public @ResponseBody Map getMtcQuestionAttributes(
			@RequestParam(value="node") String node,
			HttpSession session,HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		int unitOfLearningId = (Integer)session.getAttribute("unitOfLearningId");
		MultipleChoice multipleChoice = (MultipleChoice)addonService.getAddonByUoFandRoleName(node, unitOfLearningId);
		Map<String,Object> modelMap = new HashMap<String,Object>(3);

		if(String.valueOf(unitOfLearningId)!= null && multipleChoice!=null){
			List<Question> questionz = multipleChoice.getQuestions();
			List<String> questionsSting = new ArrayList<String>();
			List<String> answersString = new ArrayList<String>();
			Iterator it1 = questionz.iterator();
			Iterator it2 = questionz.iterator();
			int counter = 0;
			while(it1.hasNext()){
				Question question = (Question)it1.next();
				questionsSting.add(question.getQuestion());
				List<Answer> ans = question.getAnswers();
				String answerCsv = "";
				for(int i = 0; i<ans.size(); i++){
					answerCsv  = ans.get(i).getAnswer()+","+answerCsv;
				}
				answersString.add(answerCsv);
			}
			modelMap.put("qs", questionsSting);
			modelMap.put("as", answersString);
			modelMap.put("total", 1);
			modelMap.put("success", true);
		} else {
			modelMap.put("total", 0);
			modelMap.put("data", null);
			modelMap.put("failure", false);
		}

		return modelMap;
	}

	@RequestMapping(value="jsp/addons/getQuestionnAnswersAttributes.action")
	public @ResponseBody Map getQuestionnAnswersAttributes(
			@RequestParam(value="node") String node,
			HttpSession session,HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		int unitOfLearningId = (Integer)session.getAttribute("unitOfLearningId");
		QuestionsAndAnswers questionsAndAnswers = (QuestionsAndAnswers)addonService.getAddonByUoFandRoleName(node, unitOfLearningId);
		Map<String,Object> modelMap = new HashMap<String,Object>(3);

		if(String.valueOf(unitOfLearningId) != null && questionsAndAnswers!=null){
			List<Question> questionz = questionsAndAnswers.getQuestions();
			List<String> questionsSting = new ArrayList<String>();
			Iterator it1 = questionz.iterator();
			while(it1.hasNext()){
				Question question = (Question)it1.next();
				questionsSting.add(question.getQuestion());
			}
			modelMap.put("qs", questionsSting);
			modelMap.put("total", 1);
			modelMap.put("success", true);
		} else {
			modelMap.put("total", 0);
			modelMap.put("data", null);
			modelMap.put("failure", false);
		}

		return modelMap;
	}

	@RequestMapping(value="jsp/addons/saveAddonQnRAttributes.action")
	public @ResponseBody Map saveAddonQnRAttributes(
			@RequestParam(value="effort") Integer effort,
			@RequestParam(value="maxPersons") Integer maxPersons,
			@RequestParam(value="minPersons") Integer minPersons,
			@RequestParam(value="text") String text,
			HttpSession session) throws Exception {

		UnitOfLearning unitOfLearning = unitOfLearningService.get((Integer)session.getAttribute("unitOfLearningId"));
		boolean qnrExist = addonService.qnrExists(text,(Integer)session.getAttribute("unitOfLearningId"));
		Map<String,Object> modelMap = new HashMap<String,Object>(3);
		QuestionsAndAnswers questionsAndAnswers = new QuestionsAndAnswers();
		if(unitOfLearning != null ){
			if(qnrExist){
				questionsAndAnswers = (QuestionsAndAnswers) addonService.getAddonByUoFandRoleName(text,(Integer)session.getAttribute("unitOfLearningId"));
			}
			questionsAndAnswers.setTitle(text);
			questionsAndAnswers.setEffort(Effort.valueOf(effort));
			questionsAndAnswers.setMaximum(maxPersons);
			questionsAndAnswers.setMinimum(minPersons);
			questionsAndAnswers.setUnitOfLearning(unitOfLearning);
			questionsAndAnswers = (QuestionsAndAnswers) addonService.save(questionsAndAnswers);
			modelMap.put("total", 1);
			modelMap.put("questionsAndAnswers", questionsAndAnswers);
			modelMap.put("success", true);
		} else {
			modelMap.put("total", 0);
			modelMap.put("data", null);
			modelMap.put("failure", false);
		}

		return modelMap;
	}


	@RequestMapping(value="jsp/addons/saveAddonTextWorkAttributes.action")
	public @ResponseBody Map saveAddonTextWorkAttributes(
			@RequestParam(value="effort") Integer effort,
			@RequestParam(value="maxPersons") Integer maxPersons,
			@RequestParam(value="minPersons") Integer minPersons,
			@RequestParam(value="text") String text,
			HttpSession session) throws Exception {

		UnitOfLearning unitOfLearning = unitOfLearningService.get((Integer)session.getAttribute("unitOfLearningId"));
		boolean textWorkExist = addonService.textWorkExists(text,(Integer)session.getAttribute("unitOfLearningId"));
		Map<String,Object> modelMap = new HashMap<String,Object>(3);
		TextWork textWork = new TextWork();		
		if(unitOfLearning != null ){
			if(textWorkExist){
				textWork = (TextWork) addonService.getAddonByUoFandRoleName(text, (Integer)session.getAttribute("unitOfLearningId"));
			}
			textWork.setTitle(text);
			textWork.setEffort(Effort.valueOf(effort));
			textWork.setMaximum(maxPersons);
			textWork.setMinimum(minPersons);
			textWork.setUnitOfLearning(unitOfLearning);
			addonService.save(textWork);

			modelMap.put("total", 1);
			modelMap.put("textWork", textWork);
			modelMap.put("success", true);
		} else {
			modelMap.put("total", 0);
			modelMap.put("data", null);
			modelMap.put("failure", false);
		}

		return modelMap;
	}

	@RequestMapping(value="jsp/addons/saveAddonMcTAttributes.action")
	public @ResponseBody Map saveAddonMcTAttributes(
			@RequestParam(value="nuPossibleAnswers") Integer nuPossibleAnswers,
			@RequestParam(value="nuQuestions") Integer nuQuestions,
			@RequestParam(value="text") String text,
			HttpSession session) throws Exception {


		UnitOfLearning unitOfLearning = unitOfLearningService.get((Integer)session.getAttribute("unitOfLearningId"));
		boolean mctExist = addonService.mctExists(text,(Integer)session.getAttribute("unitOfLearningId"));
		Map<String,Object> modelMap = new HashMap<String,Object>(3);
		MultipleChoice multipleChoice = new MultipleChoice();
		if(mctExist){
			multipleChoice = (MultipleChoice) addonService.getAddonByUoFandRoleName(text,(Integer)session.getAttribute("unitOfLearningId"));
		}
		if(unitOfLearning != null ){

			multipleChoice.setNumberOfQuestions(nuQuestions);
			multipleChoice.setNumberOfPossibleAnswers(nuPossibleAnswers);
			multipleChoice.setTitle(text);
			multipleChoice.setUnitOfLearning(unitOfLearning);
			multipleChoice = (MultipleChoice) addonService.save(multipleChoice);

			modelMap.put("total", 1);
			modelMap.put("multipleChoice", multipleChoice);
			modelMap.put("success", true);
		} else {
			modelMap.put("total", 0);
			modelMap.put("data", null);
			modelMap.put("failure", false);
		}

		return modelMap;
	}

	@RequestMapping(value="jsp/addons/getTreeaddons.action")
	public @ResponseBody JSON treeTreeaddons(@RequestParam(value="node") String node,
			HttpSession session) throws Exception {
		int unitOfLearningId = (Integer)session.getAttribute("unitOfLearningId");

		JSON jsonObject = null;
		List<AddonDTO> addonsDTOs = new ArrayList<AddonDTO>();
		if(String.valueOf(unitOfLearningId) != null){
			if("textwork".equals(node)|| "Add-ons/Text work".equals(node) ){
				List<TextWork> listAddons = addonService.getTextWorkAddonByUoL(unitOfLearningId);
				for(TextWork textWork : listAddons){
					AddonDTO addonDTO = new AddonDTO(textWork);
					addonDTO.setText(textWork.getTitle());
					addonDTO.setId("Add-ons/Text work/"+textWork.getTitle());
					addonDTO.setLeaf(true);
					addonsDTOs.add(addonDTO);
				}
			} else if("uploadFiles".equals(node)|| "Add-ons/Uploading Files".equals(node) ){
				List<UploadingFiles> uploadingFiles = addonService.getUploadingFilesAddonByUoL(unitOfLearningId);
				for(UploadingFiles uploadingFile : uploadingFiles){
					AddonDTO addonDTO = new AddonDTO(uploadingFile);
					addonDTO.setText(uploadingFile.getTitle());
					addonDTO.setId("Add-ons/Uploading Files/"+uploadingFile.getTitle());
					addonDTO.setLeaf(true);
					addonsDTOs.add(addonDTO);
				}
			}else if("qna".equals(node)|| "Add-ons/Question and Answers".equals(node) ){
				List<QuestionsAndAnswers>  questionsAndAnswers = addonService.getQuestionsAnswersAddonByUoL(unitOfLearningId);
				for(QuestionsAndAnswers questionsAndAnswer : questionsAndAnswers){
					AddonDTO addonDTO = new AddonDTO(questionsAndAnswer);
					addonDTO.setText(questionsAndAnswer.getTitle());
					addonDTO.setId("Add-ons/Question and Answers/"+questionsAndAnswer.getTitle());
					addonDTO.setLeaf(true);
					addonsDTOs.add(addonDTO);
				}
			} else if("mct".equals(node)|| "Add-ons/Multiple-choice Test".equals(node) ){
				List<MultipleChoice> multipleChoices = addonService.getMcTestAddonByUoL(unitOfLearningId);
				for(MultipleChoice multipleChoice : multipleChoices){
					AddonDTO addonDTO = new AddonDTO(multipleChoice);
					addonDTO.setText(multipleChoice.getTitle());
					addonDTO.setId("Add-ons/Multiple-choice Test/"+multipleChoice.getTitle());
					addonDTO.setLeaf(true);
					addonsDTOs.add(addonDTO);
				}
			}else {

				AddonDTO addonTextWorkDTO = new AddonDTO();
				addonTextWorkDTO.setText("Text work");
				addonTextWorkDTO.setId("Add-ons/Text work");
				addonTextWorkDTO.setCls("folder");
				addonTextWorkDTO.setIconCls("textwork");

				AddonDTO addonUploadingFilesDTO = new AddonDTO();
				addonUploadingFilesDTO.setText("Uploading Files");
				addonUploadingFilesDTO.setId("Add-ons/Uploading Files");
				addonUploadingFilesDTO.setCls("folder");
				addonUploadingFilesDTO.setIconCls("upload");

				AddonDTO addonqnaDTO = new AddonDTO();
				addonqnaDTO.setText("Question and Answers");
				addonqnaDTO.setId("Add-ons/Question and Answers");
				addonqnaDTO.setCls("folder");
				addonqnaDTO.setIconCls("qna");

				AddonDTO addonmctDTO = new AddonDTO();
				addonmctDTO.setText("Multiple-choice Test");
				addonmctDTO.setId("Add-ons/Multiple-choice Test");
				addonmctDTO.setCls("folder");
				addonmctDTO.setIconCls("multiplechoice");

				addonsDTOs.add(addonTextWorkDTO);
				addonsDTOs.add(addonUploadingFilesDTO);
				addonsDTOs.add(addonqnaDTO);
				addonsDTOs.add(addonmctDTO);
			}

			JsonConfig jsonConfig = new JsonConfig();
			jsonObject = JSONSerializer.toJSON(addonsDTOs, jsonConfig);
		}
		return jsonObject;
	}




	@RequestMapping(value="jsp/addons/getAttributes.action")
	public @ResponseBody Map getRoleAttributes(
			@RequestParam(value="addonsToEdit") String stringAddon,
			HttpSession session) throws Exception {

		int unitOfLearningId = (Integer)session.getAttribute("unitOfLearningId");
		boolean addonExists = addonService.addonNameExists(stringAddon,unitOfLearningId);
		Map<String,Object> modelMap = new HashMap<String,Object>(3);

		if(String.valueOf(unitOfLearningId) != null && addonExists==true){
			Addon addon = addonService.getAddonByUoFandRoleName(stringAddon,unitOfLearningId);
			EditAddonDTO editAddonDTO = new EditAddonDTO(addon);
			modelMap.put(editAddonDTO.getAddonInstance(), editAddonDTO);
			modelMap.put("total", 1);
			modelMap.put("success", true);
		} else {
			modelMap.put("total", 0);
			modelMap.put("data", null);
			modelMap.put("failure", false);
		}

		return modelMap;
	}



	@RequestMapping(value="jsp/addons/text.action")
	public @ResponseBody Map saveAddonTextWorkTitle(
			@RequestParam(value="title") String title,
			HttpSession session) throws Exception {

		UnitOfLearning unitOfLearning = unitOfLearningService.get((Integer)session.getAttribute("unitOfLearningId"));
		boolean textWorkExist = addonService.textWorkExists(title,(Integer)session.getAttribute("unitOfLearningId"));
		Map<String,Object> modelMap = new HashMap<String,Object>(3);
		TextWork textWork = new TextWork();		
		if(unitOfLearning != null ){
			if(textWorkExist){
				textWork = (TextWork) addonService.getAddonByUoFandRoleName(title, (Integer)session.getAttribute("unitOfLearningId"));
			}
			textWork.setTitle(title);
			textWork.setUnitOfLearning(unitOfLearning);
			addonService.save(textWork);

			modelMap.put("total", 1);
			modelMap.put("textWork", textWork);
			modelMap.put("success", true);
		} else {
			modelMap.put("total", 0);
			modelMap.put("data", null);
			modelMap.put("failure", false);
		}

		return modelMap;
	}


	@RequestMapping(value="jsp/addons/uf.action")
	public @ResponseBody Map saveAddonQnRTitle(
			@RequestParam(value="title") String title,
			HttpSession session) throws Exception {

		UnitOfLearning unitOfLearning = unitOfLearningService.get((Integer)session.getAttribute("unitOfLearningId"));
		boolean ufExist = addonService.uploadingFilesExists(title,(Integer)session.getAttribute("unitOfLearningId"));
		Map<String,Object> modelMap = new HashMap<String,Object>(3);
		UploadingFiles uploadingFiles = new UploadingFiles();
		if(unitOfLearning != null ){
			if(ufExist){
				uploadingFiles = (UploadingFiles) addonService.getAddonByUoFandRoleName(title,(Integer)session.getAttribute("unitOfLearningId"));
			}
			uploadingFiles.setTitle(title);
			uploadingFiles.setUnitOfLearning(unitOfLearning);
			uploadingFiles = (UploadingFiles) addonService.save(uploadingFiles);

			modelMap.put("total", 1);
			modelMap.put("uploadingFiles", uploadingFiles);
			modelMap.put("success", true);
		} else {
			modelMap.put("total", 0);
			modelMap.put("data", null);
			modelMap.put("failure", false);
		}
		return modelMap;
	}


	@RequestMapping(value="jsp/addons/qnr.action")
	public @ResponseBody Map saveAddonUploadingFilesTitle(
			@RequestParam(value="title") String title,
			HttpSession session) throws Exception {

		UnitOfLearning unitOfLearning = unitOfLearningService.get((Integer)session.getAttribute("unitOfLearningId"));
		boolean qnrExist = addonService.uploadingFilesExists(title,(Integer)session.getAttribute("unitOfLearningId"));
		Map<String,Object> modelMap = new HashMap<String,Object>(3);
		QuestionsAndAnswers questionsAndAnswers = new QuestionsAndAnswers();
		if(qnrExist){
			questionsAndAnswers = (QuestionsAndAnswers) addonService.getAddonByUoFandRoleName(title,(Integer)session.getAttribute("unitOfLearningId"));
		}
		if(unitOfLearning != null ){

			questionsAndAnswers.setTitle(title);
			questionsAndAnswers.setUnitOfLearning(unitOfLearning);
			addonService.save(questionsAndAnswers);

			modelMap.put("total", 1);
			modelMap.put("questionsAndAnswers", questionsAndAnswers);
			modelMap.put("success", true);
		} else {
			modelMap.put("total", 0);
			modelMap.put("data", null);
			modelMap.put("failure", false);
		}

		return modelMap;
	}

	@RequestMapping(value="jsp/addons/mtc.action")
	public @ResponseBody Map saveAddonMtCTitle(
			@RequestParam(value="title") String title,
			HttpSession session) throws Exception {

		UnitOfLearning unitOfLearning = unitOfLearningService.get((Integer)session.getAttribute("unitOfLearningId"));
		boolean mctExist = addonService.mctExists(title,(Integer)session.getAttribute("unitOfLearningId"));
		Map<String,Object> modelMap = new HashMap<String,Object>(3);

		if(unitOfLearning != null && mctExist!=true){
			MultipleChoice multipleChoice = new MultipleChoice();
			multipleChoice.setTitle(title);
			multipleChoice.setUnitOfLearning(unitOfLearning);
			multipleChoice = (MultipleChoice) addonService.save(multipleChoice);

			modelMap.put("total", 1);
			modelMap.put("multipleChoice", multipleChoice);
			modelMap.put("success", true);
		} else {
			modelMap.put("total", 0);
			modelMap.put("data", null);
			modelMap.put("failure", false);
		}

		return modelMap;
	}


	@RequestMapping(value="jsp/addons/laGrid.action")
	public @ResponseBody Map<String, Object> fsGridView(
			HttpSession session,
			@RequestParam(value="limit",required=false) Integer limit,
			@RequestParam(value="page",required=false) Integer page,
			@RequestParam(value="start",required=false) Integer start,
			@RequestParam(value="data",required=false) List<String> data
			//			@RequestParam(value="dataFromGrid",required=false) List<String> dataFromGrid
			) throws Exception {

		int unitOfLearningId = (Integer)session.getAttribute("unitOfLearningId");
		String activityId = (String)session.getAttribute("graphId");
		String[] activityType = activityId.split(":");
		Activity activity = activityService.getbyGraphId(activityType[1]);
		List<Addon> uolAddons = addonService.getAddonsByUoL(unitOfLearningId);
		List<Addon> activityAddons = new ArrayList<Addon>();
		HashMap<Integer, AddonDTO> addonDTOHash = new HashMap<Integer, AddonDTO>();
		if(!activity.getAddons().isEmpty()){
			activityAddons = activity.getAddons();
		}
		
		List<AddonDTO> addonDTOs = new ArrayList<AddonDTO>();
		if(data==null){//just view them
			if(!activityAddons.isEmpty()){
				for(Addon addon : activityAddons){
					AddonDTO addonDTO = new AddonDTO();
					addonDTO.setText(addon.getTitle());
					addonDTO.setId(String.valueOf(addon.getId()));
					addonDTO.setEnable(true);
					if(addon instanceof TextWork){
						addonDTO.setType("TextWork");
					}else if(addon instanceof UploadingFiles){
						addonDTO.setType("UploadingFiles");
					}else if(addon instanceof QuestionsAndAnswers){
						addonDTO.setType("QuestionsAndAnswers");
					}else if(addon instanceof MultipleChoice){
						addonDTO.setType("MultipleChoice");
					}
					addonDTOHash.put(addon.getId(), addonDTO);
				}

				for(Addon addon : uolAddons){
					if(!addonDTOHash.containsKey(addon.getId())){
						AddonDTO addonDTO = new AddonDTO();
						addonDTO.setText(addon.getTitle());
						addonDTO.setId(String.valueOf(addon.getId()));
						addonDTO.setEnable(false);
						if(addon instanceof TextWork){
							addonDTO.setType("TextWork");
						}else if(addon instanceof UploadingFiles){
							addonDTO.setType("UploadingFiles");
						}else if(addon instanceof QuestionsAndAnswers){
							addonDTO.setType("QuestionsAndAnswers");
						}else if(addon instanceof MultipleChoice){
							addonDTO.setType("MultipleChoice");
						}
						addonDTOHash.put(addon.getId(), addonDTO);
					}
				}
			}else{
				for(Addon addon : uolAddons){
						AddonDTO addonDTO = new AddonDTO();
						addonDTO.setText(addon.getTitle());
						addonDTO.setId(String.valueOf(addon.getId()));
						addonDTO.setEnable(false);
						if(addon instanceof TextWork){
							addonDTO.setType("TextWork");
						}else if(addon instanceof UploadingFiles){
							addonDTO.setType("UploadingFiles");
						}else if(addon instanceof QuestionsAndAnswers){
							addonDTO.setType("QuestionsAndAnswers");
						}else if(addon instanceof MultipleChoice){
							addonDTO.setType("MultipleChoice");
						}
						addonDTOHash.put(addon.getId(), addonDTO);
				}
			}
			Iterator<AddonDTO> it = addonDTOHash.values().iterator();
			while(it.hasNext()){
				addonDTOs.add((AddonDTO) it.next());
			}
		}else{
			List<Addon> actAddons = new ArrayList<Addon>();
			for(int i=0;i<data.size();){
				AddonDTO addonDTO = new AddonDTO();
				addonDTO.setType(data.get(i++));
				addonDTO.setText(data.get(i++));
				addonDTO.setEnable(Boolean.valueOf(data.get(i++)));
				addonDTOs.add(addonDTO);
			}
			for(AddonDTO dto : addonDTOs){
				if("TextWork".equals(dto.getType()) && dto.isEnable()){
					TextWork textWork = (TextWork)addonService.getAddonByUoFandRoleName(dto.getText(), unitOfLearningId);
					actAddons.add(textWork);
				}else if("UploadingFiles".equals(dto.getType()) && dto.isEnable()){
					UploadingFiles uploadingFiles = (UploadingFiles)addonService.getAddonByUoFandRoleName(dto.getText(), unitOfLearningId);
					actAddons.add(uploadingFiles);
				}else if("QuestionsAndAnswers".equals(dto.getType()) && dto.isEnable()){
					QuestionsAndAnswers questionsAndAnswers = (QuestionsAndAnswers)addonService.getAddonByUoFandRoleName(dto.getText(), unitOfLearningId);
					actAddons.add(questionsAndAnswers);
				}else if("MultipleChoice".equals(dto.getType()) && dto.isEnable()){
					MultipleChoice multipleChoice = (MultipleChoice)addonService.getAddonByUoFandRoleName(dto.getText(), unitOfLearningId);
					actAddons.add(multipleChoice);
				}
			}
			activity.setAddons(actAddons);
			activityService.save(activity);
		}

		Map<String,Object> modelMap = new HashMap<String,Object>(3);
		modelMap.put("items", addonDTOs);
		modelMap.put("total", addonDTOs.size());
		modelMap.put("success", true);

		return modelMap;
	}
	
	

	@RequestMapping(value="jsp/addons/saGrid.action")
	public @ResponseBody Map<String, Object> saGridView(
			HttpSession session,
			@RequestParam(value="limit",required=false) Integer limit,
			@RequestParam(value="page",required=false) Integer page,
			@RequestParam(value="start",required=false) Integer start,
			@RequestParam(value="data",required=false) List<String> data
			//			@RequestParam(value="dataFromGrid",required=false) List<String> dataFromGrid
			) throws Exception {

		int unitOfLearningId = (Integer)session.getAttribute("unitOfLearningId");
		String activityId = (String)session.getAttribute("graphId");
		String[] activityType = activityId.split(":");
		Activity activity = activityService.getbyGraphId(activityType[1]);
		List<Addon> uolAddons = addonService.getAddonsByUoL(unitOfLearningId);
		List<Addon> activityAddons = new ArrayList<Addon>();
		HashMap<Integer, AddonDTO> addonDTOHash = new HashMap<Integer, AddonDTO>();
		if(!activity.getAddons().isEmpty()){
			activityAddons = activity.getAddons();
		}
		
		List<AddonDTO> addonDTOs = new ArrayList<AddonDTO>();
		if(data==null){//just view them
			if(!activityAddons.isEmpty()){
				for(Addon addon : activityAddons){
					AddonDTO addonDTO = new AddonDTO();
					addonDTO.setText(addon.getTitle());
					addonDTO.setId(String.valueOf(addon.getId()));
					addonDTO.setEnable(true);
					if(addon instanceof TextWork){
						addonDTO.setType("TextWork");
					}else if(addon instanceof UploadingFiles){
						addonDTO.setType("UploadingFiles");
					}else if(addon instanceof QuestionsAndAnswers){
						addonDTO.setType("QuestionsAndAnswers");
					}else if(addon instanceof MultipleChoice){
						addonDTO.setType("MultipleChoice");
					}
					addonDTOHash.put(addon.getId(), addonDTO);
				}
				
				for(Addon addon : uolAddons){
					if(!addonDTOHash.containsKey(addon.getId())){
						AddonDTO addonDTO = new AddonDTO();
						addonDTO.setText(addon.getTitle());
						addonDTO.setId(String.valueOf(addon.getId()));
						addonDTO.setEnable(false);
						if(addon instanceof TextWork){
							addonDTO.setType("TextWork");
						}else if(addon instanceof UploadingFiles){
							addonDTO.setType("UploadingFiles");
						}else if(addon instanceof QuestionsAndAnswers){
							addonDTO.setType("QuestionsAndAnswers");
						}else if(addon instanceof MultipleChoice){
							addonDTO.setType("MultipleChoice");
						}
						addonDTOHash.put(addon.getId(), addonDTO);
					}
				}
			}else{
				for(Addon addon : uolAddons){
						AddonDTO addonDTO = new AddonDTO();
						addonDTO.setText(addon.getTitle());
						addonDTO.setId(String.valueOf(addon.getId()));
						addonDTO.setEnable(false);
						if(addon instanceof TextWork){
							addonDTO.setType("TextWork");
						}else if(addon instanceof UploadingFiles){
							addonDTO.setType("UploadingFiles");
						}else if(addon instanceof QuestionsAndAnswers){
							addonDTO.setType("QuestionsAndAnswers");
						}else if(addon instanceof MultipleChoice){
							addonDTO.setType("MultipleChoice");
						}
						addonDTOHash.put(addon.getId(), addonDTO);
				}
			}
			Iterator<AddonDTO> it = addonDTOHash.values().iterator();
			while(it.hasNext()){
				addonDTOs.add((AddonDTO) it.next());
			}
		}else{
			List<Addon> actAddons = new ArrayList<Addon>();
			for(int i=0;i<data.size();){
				AddonDTO addonDTO = new AddonDTO();
				addonDTO.setType(data.get(i++));
				addonDTO.setText(data.get(i++));
				addonDTO.setEnable(Boolean.valueOf(data.get(i++)));
				addonDTOs.add(addonDTO);
			}
			for(AddonDTO dto : addonDTOs){
				if("TextWork".equals(dto.getType()) && dto.isEnable()){
					TextWork textWork = (TextWork)addonService.getAddonByUoFandRoleName(dto.getText(), unitOfLearningId);
					actAddons.add(textWork);
				}else if("UploadingFiles".equals(dto.getType()) && dto.isEnable()){
					UploadingFiles uploadingFiles = (UploadingFiles)addonService.getAddonByUoFandRoleName(dto.getText(), unitOfLearningId);
					actAddons.add(uploadingFiles);
				}else if("QuestionsAndAnswers".equals(dto.getType()) && dto.isEnable()){
					QuestionsAndAnswers questionsAndAnswers = (QuestionsAndAnswers)addonService.getAddonByUoFandRoleName(dto.getText(), unitOfLearningId);
					actAddons.add(questionsAndAnswers);
				}else if("MultipleChoice".equals(dto.getType()) && dto.isEnable()){
					MultipleChoice multipleChoice = (MultipleChoice)addonService.getAddonByUoFandRoleName(dto.getText(), unitOfLearningId);
					actAddons.add(multipleChoice);
				}
			}
			activity.setAddons(actAddons);
			activityService.save(activity);
		}

		Map<String,Object> modelMap = new HashMap<String,Object>(3);
		modelMap.put("items", addonDTOs);
		modelMap.put("total", addonDTOs.size());
		modelMap.put("success", true);

		return modelMap;
	}

	public IUnitOfLearningService getUnitOfLearningService() {
		return unitOfLearningService;
	}
	@Resource(name="unitOfLearningService")
	public void setUnitOfLearningService(IUnitOfLearningService unitOfLearningService) {
		this.unitOfLearningService = unitOfLearningService;
	}
	public IQuestionService getQuestionService() {
		return questionService;
	}
	@Resource(name="questionService")
	public void setQuestionService(IQuestionService questionService) {
		this.questionService = questionService;
	}
	public IMultipleChoiceService getMultipleChoiceService() {
		return multipleChoiceService;
	}
	@Resource(name="multipleChoiceService")
	public void setMultipleChoiceService(IMultipleChoiceService multipleChoiceService) {
		this.multipleChoiceService = multipleChoiceService;
	}
	public IAnswerService getAnswerService() {
		return answerService;
	}
	@Resource(name="answerService")
	public void setAnswerService(IAnswerService answerService) {
		this.answerService = answerService;
	}
	public IAddonService getAddonService() {
		return addonService;
	}
	@Resource(name="addonService")
	public void setAddonService(IAddonService addonService) {
		this.addonService = addonService;
	}
	public IActivityService getActivityService() {
		return activityService;
	}
	@Resource(name="activityService")
	public void setActivityService(IActivityService activityService) {
		this.activityService = activityService;
	}
}
